//IE9(含)以下浏览器用到的jsonp回调函数
import webim from "./imSdk"
export default {
  data() {
    return {
      isImJoin:false
    }
  },
  methods: {
    applyJoinBigGroup(groupId, callback) {
      var options = {
        GroupId: groupId //群id
      };
      webim.applyJoinBigGroup(
        options,
        resp => {
          //JoinedSuccess:加入成功; WaitAdminApproval:等待管理员审批
          if (resp.JoinedStatus && resp.JoinedStatus == "JoinedSuccess") {
            console.log("join succ");
            this.isImJoin = true
            callback && callback();
            //webim.Log.info('进群成功');
            //selToID = groupId;
          } else {
            console.log("进群失败",resp.ErrorInfo);
          }
        },
        err => {
          // alert(err.ErrorInfo);
          console.log("进群失败",err.ErrorInfo);
        }
      );
    },
    convertTextMsgToHtml(content) {
      return content.getText();
    },
    convertMsgtoHtml(msg) {
      //alert("go to ")
      var html = "",
        elems,
        elem,
        type,
        content;
      elems = msg.getElems(); //获取消息包含的元素数组
      for (var i in elems) {
        elem = elems[i];
        type = elem.getType(); //获取元素类型
        content = elem.getContent(); //获取元素对象
        switch (type) {
          case webim.MSG_ELEMENT_TYPE.TEXT:
            html += this.convertTextMsgToHtml(content);
            break;
          case webim.MSG_ELEMENT_TYPE.FACE:
            html += this.convertFaceMsgToHtml(content);
            break;
          case webim.MSG_ELEMENT_TYPE.IMAGE:
            html += this.convertImageMsgToHtml(content);
            break;
          case webim.MSG_ELEMENT_TYPE.SOUND:
            html += this.convertSoundMsgToHtml(content);
            break;
          case webim.MSG_ELEMENT_TYPE.FILE:
            html += this.convertFileMsgToHtml(content);
            break;
          case webim.MSG_ELEMENT_TYPE.LOCATION: //暂不支持地理位置
            //html += convertLocationMsgToHtml(content);
            break;
          case webim.MSG_ELEMENT_TYPE.CUSTOM:
            try {
              let cusMsg = JSON.parse(content.data);
              if (cusMsg.type) {
                switch (cusMsg.type) {
                  case "member":
                    //console.log("get member custom msg", content);
                    this.updateMember(cusMsg.num);
                    break;
                  case "dongdong":
                    this.pushVote(cusMsg.data);
                    break;
                  case "pmd":
                    //console.log(cusMsg)
                    this.pmdData(cusMsg);
                    break;
                  case "reply"://回复消息
                    this.replyMessage(cusMsg.data)
                    break;
                  case "gffy"://直播间小助手发言
                    this.heaperMessage(msg)
                    break;
                  case "hongbao":
                    //console.log(cusMsg.data)
                    this.hongbaostartruan(cusMsg.data)
                    break;
                  case "hdCount":
                    this.updateHdCount && this.updateHdCount(cusMsg.num);
                    break;
                  case "love":
                    this.appendLoveMsg && this.appendLoveMsg({"un":msg.fromAccount,"nick":msg.fromAccountNick,"headImg":msg.fromAccountHeadurl});
                    break;
                  case "gift":
                    this.appendGiftMsg && this.appendGiftMsg({"un":msg.fromAccount,"nick":msg.fromAccountNick,"headImg":msg.fromAccountHeadurl,"data":cusMsg.data});
                    break;
                  default:
                }
              }
            } catch (e) {}
            return "";
            //html += this.convertCustomMsgToHtml(content);
            break;
          case webim.MSG_ELEMENT_TYPE.GROUP_TIP:
            html += this.convertGroupTipMsgToHtml(content);
            break;
          default:
            webim.Log.error("未知消息元素类型: elemType=" + type);
            break;
        }
      }
      return webim.Tool.formatHtml2Text(html);
    },

    iniIm(sdkId,acType,roomid, ac, nickname, headerImg, sign, callback) {
      let _this = this;
      if(_this.isImJoin){
        _this.isImJoin = false
        webim.quitBigGroup(
          {'GroupId': roomid},
          function(resp) {
            _this.iniIm(sdkId,acType,roomid, ac, nickname, headerImg, sign, callback)
          },
          function(err) {
            _this.iniIm(sdkId,acType,roomid, ac, nickname, headerImg, sign, callback)
          }
        );
        return;
      }
      //console.log("roomid是", roomid, ac, nickname, headerImg, sign);

      let loginInfo = {
        sdkAppID: sdkId, // 用户所属应用id,必填
        appIDAt3rd: sdkId, // 用户所属应用id，必填
        accountType: acType, // 用户所属应用帐号类型，必填
        identifier: ac, // 当前用户ID,必须是否字符串类型，选填
        identifierNick: nickname, // 当前用户昵称，选填
        //eJxFkF1vgjAYhf8Lty5bW*h0uwOCS5MiLmjIvGkILVrlo4M62yz772MNZrfPk5P3Pefb29H8sVRKclZq5g-ce-WA9*CwMEoOgpW1FsOEIcYYAXC3X2IYZd9NAgGIIfIB*JeSi07LWrqgFqOGsxjlcSJp8hGT91gseptkqr6uTB0GyiZqS-frghaWoG11aGJuonixQuYlJKeQXE47QDW*fW6W0VsGDzQNU9usbxtisxxG5yY3RfvUpllxP8YvzHX7*z4AAD4jDPxZatkK1ypAQQCXEM28rKr*2mmmrRJujJ9fkAhXeA__
        userSig: sign, // 当前用户身份凭证，必须是字符串类型，选填
        headurl: headerImg
      };

      // 监听（多终端同步）群系统消息方法，方法都定义在demo_group_notice.js文件中
      // 注意每个数字代表的含义，比如，
      // 1表示监听申请加群消息，2表示监听申请加群被同意消息，3表示监听申请加群被拒绝消息等
      let onGroupSystemNotifys = {
        // "1": onApplyJoinGroupRequestNotify, //申请加群请求（只有管理员会收到,暂不支持）
        // "2": onApplyJoinGroupAcceptNotify, //申请加群被同意（只有申请人能够收到,暂不支持）
        // "3": onApplyJoinGroupRefuseNotify, //申请加群被拒绝（只有申请人能够收到,暂不支持）
        // "4": onKickedGroupNotify, //被管理员踢出群(只有被踢者接收到,暂不支持)
        "5": this.onDestoryGroupNotify, // 群被解散(全员接收)
        // "6": onCreateGroupNotify, //创建群(创建者接收,暂不支持)
        // "7": onInvitedJoinGroupNotify, //邀请加群(被邀请者接收,暂不支持)
        // "8": onQuitGroupNotify, //主动退群(主动退出者接收,暂不支持)
        // "9": onSetedGroupAdminNotify, //设置管理员(被设置者接收,暂不支持)
        // "10": onCanceledGroupAdminNotify, //取消管理员(被取消者接收,暂不支持)
        "11": this.onRevokeGroupNotify, // 群已被回收(全员接收)
        "255": this.onCustomGroupNotify // 用户自定义通知(默认全员接收)
      };



      // 监听连接状态回调变化事件
      let onConnNotify = function(resp) {
        switch (resp.ErrorCode) {
          case webim.CONNECTION_STATUS.ON:
            // webim.Log.warn('连接状态正常...');
            break;
          case webim.CONNECTION_STATUS.OFF:
          if(!_this.isImReTry){
              _this.isImReTry = true
              console.log("连接状态已经断开,开始重连...")
              setTimeout(()=>{
                _this.iniIm(sdkId,acType,roomid, ac, nickname, headerImg, sign, callback)
              },1000)
            }
            break;
          default:
            console.log("未知连接状态,status=" , resp.ErrorCode);
            break;
        }
      };

      // 监听事件
      let listeners = {
        onConnNotify: onConnNotify, // 选填
        //jsonpCallback: this.jsonpCallback, // IE9(含)以下浏览器用到的jsonp回调函数,移动端可不填，pc端必填
        onBigGroupMsgNotify: this.onBigGroupMsgNotify, // 监听新消息(大群)事件，必填
        onMsgNotify: this.onMsgNotify, // 监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
        onGroupSystemNotifys: onGroupSystemNotifys, // 监听（多终端同步）群系统消息事件，必填
        onGroupInfoChangeNotify: this.onGroupInfoChangeNotify // 监听群资料变化事件，选填
      };
      //console.log("loginInfo",loginInfo)
      let options = {
        isAccessFormalEnv: true, // 是否访问正式环境，默认访问正式，选填
        isLogOn: false // 是否开启控制台打印日志,默认开启，选填
      };
      //console.log("loginInfo is",loginInfo)
      webim.login(
        loginInfo,
        listeners,
        options,
        function(user) {
          _this.isImReTry = false
          _this.setImUserInfo({ nickname: _this.$store.state.userInfo.nickname, img: _this.$store.state.userInfo.wxpic });
          console.log("login succ userInfo", user);
          // identifierNick为登录用户昵称(没有设置时，为帐号)，无登录态时为空
          //webim.Log.info("webim登录成功");

          webim.quitBigGroup(
            {'GroupId': roomid},
            function(resp) {
              _this.applyJoinBigGroup(roomid, callback); // 加入大群
            },
            function(err) {
              _this.applyJoinBigGroup(roomid, callback); // 加入大群
            }
          );

          // this.hideDiscussForm(); //隐藏评论表单
          // base.initEmotionUL(); //初始化表情
        },
        function(err) {
          _this.isImReTry = false
          console.log("login err is", err);
          setTimeout(()=>{
            _this.iniIm(sdkId,acType,roomid, ac, nickname, headerImg, sign, callback)
          },3000)

        }
      );
    },
    setImUserInfo(user) {
      let option = [];
      if (user.nickname) {
        option.push({
          Tag: "Tag_Profile_IM_Nick",
          Value: user.nickname
        });
      }

      if (user.img) {
        option.push({
          Tag: "Tag_Profile_IM_Image",
          Value: user.img
        });
      }

      /* {
            'Tag': 'Tag_Profile_IM_Gender',
            'Value': 'Gender_Type_Male',
          }, */

      webim.setProfilePortrait(
        {
          ProfileItem: option
        },
        res => {
          console.log("同步用户信息 succ res", res);
        },
        err => {
          console.log("err", err);
        }
      );
    },

    getImUserInfo(user = []) {
      webim.getProfilePortrait(
        {
          To_Account: user,
          TagList: [
            "Tag_Profile_IM_Nick",
            "Tag_Profile_IM_Gender",
            "Tag_Profile_IM_Image"
          ]
        },
        res => {
          console.log("succ res", res);
        },
        err => {
          console.log("err", err);
        }
      );
    },
    onBigGroupMsgNotify(msgList) {
      //console.log('onBigGroupMsgNotify msg', msgList)
      for (let i = msgList.length - 1; i >= 0; i--) {
        // 遍历消息，按照时间从后往前
        let msg = msgList[i];
        // console.warn(msg);
        // 显示收到的消息
        // alert("msg "+msg.getFromAccount())
        this.getMessage(msg);
      }
    },
    SendImMsg(msgtosend) {//type  0  是正常留言    3是答题
      if (this.roomId == "") {
        //alert('您还没有进入房间，暂不能聊天')
        return;
      }
      let msgLen = webim.Tool.getStrBytes(msgtosend);

      if (msgtosend.length < 1) {
        //alert('发送的消息不能为空!')
        return;
      }

      let maxLen, errInfo;
      if (this.selType == webim.SESSION_TYPE.GROUP) {
        maxLen = webim.MSG_MAX_LENGTH.GROUP;
        errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "个汉字)";
      } else {
        maxLen = webim.MSG_MAX_LENGTH.C2C;
        errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "个汉字)";
      }
      if (msgLen > maxLen) {
        console.log(errInfo);
        return;
      }

      if (!this.selSess) {
        this.selSess = new webim.Session(
          this.selType,
          this.roomId,
          this.roomId,
          this.selSessHeadUrl,
          Math.round(new Date().getTime() / 1000)
        );
      }

      let isSend = true; // 是否为自己发送
      let seq = -1; // 消息序列，-1表示sdk自动生成，用于去重
      let random = Math.round(Math.random() * 4294967296); // 消息随机数，用于去重
      let msgTime = Math.round(new Date().getTime() / 1000); // 消息时间戳
      let subType; // 消息子类型
      if (this.selType == webim.SESSION_TYPE.GROUP) {
        // 群消息子类型如下：
        // webim.GROUP_MSG_SUB_TYPE.COMMON-普通消息,
        // webim.GROUP_MSG_SUB_TYPE.LOVEMSG-点赞消息，优先级最低
        // webim.GROUP_MSG_SUB_TYPE.TIP-提示消息(不支持发送，用于区分群消息子类型)，
        // webim.GROUP_MSG_SUB_TYPE.REDPACKET-红包消息，优先级最高
        subType = webim.GROUP_MSG_SUB_TYPE.COMMON;
      } else {
        // C2C消息子类型如下：
        // webim.C2C_MSG_SUB_TYPE.COMMON-普通消息,
        subType = webim.C2C_MSG_SUB_TYPE.COMMON;
      }
      let msg = new webim.Msg(
        this.selSess,
        isSend,
        seq,
        random,
        msgTime,
        this.un,
        subType,
        this.nikename,
      );
      // 解析文本和表情
      let expr = /\[[^[\]]{1,3}\]/gm;
      let emotions = msgtosend.match(expr);
      let text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex;
      if (!emotions || emotions.length < 1) {
        text_obj = new webim.Msg.Elem.Text(msgtosend);
        msg.addText(text_obj);
      } else {
        // 有表情
        for (let i = 0; i < emotions.length; i++) {
          tmsg = msgtosend.substring(0, msgtosend.indexOf(emotions[i]));
          if (tmsg) {
            text_obj = new webim.Msg.Elem.Text(tmsg);
            msg.addText(text_obj);
          }
          emotionIndex = webim.EmotionDataIndexs[emotions[i]];
          emotion = webim.Emotions[emotionIndex];
          if (emotion) {
            face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i]);
            msg.addFace(face_obj);
          } else {
            text_obj = new webim.Msg.Elem.Text(emotions[i]);
            msg.addText(text_obj);
          }
          restMsgIndex = msgtosend.indexOf(emotions[i]) + emotions[i].length;
          msgtosend = msgtosend.substring(restMsgIndex);
        }
        if (msgtosend) {
          text_obj = new webim.Msg.Elem.Text(msgtosend);
          msg.addText(text_obj);
        }
      }
      let _this = this
      webim.sendMsg(
        msg,
        function(resp) {
          //webim.Log.info('发消息成功')
          //console.log(resp)
          //_this.sendDatabaseMsg()
        },
        function(err) {
          //webim.Log.error('发消息失败:' + err.ErrorInfo)
          console.log("发消息失败:", err);
          _this.bannedToPost(err)//禁言liveMsg
        }
      );
    },
    sendLoveMsg() {
      if (this.roomId == "") {
        //alert("您还没有进入房间，暂不能点赞");
        return;
      }

      if (!this.selSess) {
        this.selSess = new webim.Session(
          this.selType,
          this.roomId,
          this.roomId,
          this.selSessHeadUrl,
          Math.round(new Date().getTime() / 1000)
        );
      }
      let isSend = true; //是否为自己发送
      let seq = -1; //消息序列，-1表示sdk自动生成，用于去重
      let random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
      let msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
      //群消息子类型如下：
      //webim.GROUP_MSG_SUB_TYPE.COMMON-普通消息,
      //webim.GROUP_MSG_SUB_TYPE.LOVEMSG-点赞消息，优先级最低
      //webim.GROUP_MSG_SUB_TYPE.TIP-提示消息(不支持发送，用于区分群消息子类型)，
      //webim.GROUP_MSG_SUB_TYPE.REDPACKET-红包消息，优先级最高
      let subType = webim.GROUP_MSG_SUB_TYPE.LOVEMSG;

      let msg = new webim.Msg(
        this.selSess,
        isSend,
        seq,
        random,
        msgTime,
        this.un,
        subType,
        this.nikename
      );
      let msgtosend = "dz";
      let text_obj = new webim.Msg.Elem.Text(msgtosend);
      msg.addText(text_obj);

      webim.sendMsg(
        msg,
        function(resp) {
          /*       if (selType == webim.SESSION_TYPE.C2C) { //私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息
                  showMsg(msg);
               }*/
          console.info("点赞成功");
        },
        function(err) {
          //webim.Log.error("发送点赞消息失败:" + err.ErrorInfo);
          console.log("发送点赞消息失败:", err.ErrorInfo);
        }
      );
    },
    livetime: function(type) {
      return type;
      // if (typeof type === "undefined") {
      //   return type;
      // } else {
      //   return type.slice(5, 10) + " " + type.slice(11, 16);
      // }
    },
    convertGroupTipMsgToHtml(content) {
      //console.log("content is ",content)
      var WEB_IM_GROUP_TIP_MAX_USER_COUNT = 10;
      var text = "";
      var maxIndex = WEB_IM_GROUP_TIP_MAX_USER_COUNT - 1;
      var opType, opUserId, userIdList;
      var memberCount;
      opType = content.getOpType(); //群提示消息类型（操作类型）
      opUserId = content.getOpUserId(); //操作人id
      userIdList = content.getUserInfo();
      //console.log("join room ",userIdList)
      switch (opType) {
        case webim.GROUP_TIP_TYPE.JOIN: //加入群
          //text += opUserId + "邀请了";
          for (var m in userIdList) {
            let nick = ''
            if (userIdList[m].NickName != undefined) {
              nick = userIdList[m].NickName ;
            } else {
              nick= userIdList[m].UserId ;
            }
             //console.log(nick)
             this.enterRoomPersonTip(nick);//进入直播间提示
      /*      if (userIdList.length > WEB_IM_GROUP_TIP_MAX_USER_COUNT && m == maxIndex) {
              text += "等" + userIdList.length + "人";
              break;
            }*/
          }
          text = text.substring(0, text.length - 1);
          text += "进入直播间";
          break;
        case webim.GROUP_TIP_TYPE.QUIT: //退出群
             //console.log('退群')
          break;
        case webim.GROUP_TIP_TYPE.KICK: //踢出群

          break;
        case webim.GROUP_TIP_TYPE.SET_ADMIN: //设置管理员

          break;
        case webim.GROUP_TIP_TYPE.CANCEL_ADMIN: //取消管理员

          break;

        case webim.GROUP_TIP_TYPE.MODIFY_GROUP_INFO: //群资料变更

          break;

        case webim.GROUP_TIP_TYPE.MODIFY_MEMBER_INFO: //群成员资料变更(禁言时间)

          break;
        default:
          break;
      }
      return text;
},
    onRevokeGroupNotify(notify) {
      webim.Log.warn("执行 群被回收 回调：" + JSON.stringify(notify));
      var reportTypeCh = "[群被回收]";
      var content = "该群已被回收";
      showGroupSystemMsg(
        notify.ReportType,
        reportTypeCh,
        notify.GroupId,
        notify.GroupName,
        content,
        notify.MsgTime
      );
    },
    onCustomGroupNotify(notify) {
      webim.Log.warn("执行 用户自定义系统消息 回调：" + JSON.stringify(notify));
      var reportTypeCh = "[用户自定义系统消息]";
      var content = notify.UserDefinedField; //群自定义消息数据
      showGroupSystemMsg(
        notify.ReportType,
        reportTypeCh,
        notify.GroupId,
        notify.GroupName,
        content,
        notify.MsgTime
      );
    },
    onDestoryGroupNotify(notify) {
      webim.Log.warn("执行 解散群 回调：" + JSON.stringify(notify));
      var reportTypeCh = "[群被解散]";
      var content = "群主" + notify.Operator_Account + "已解散该群";
      showGroupSystemMsg(
        notify.ReportType,
        reportTypeCh,
        notify.GroupId,
        notify.GroupName,
        content,
        notify.MsgTime
      );
    },
    onGroupInfoChangeNotify(groupInfo) {
      webim.Log.warn("执行 群资料变化 回调： " + JSON.stringify(groupInfo));
      var groupId = groupInfo.GroupId;
      var newFaceUrl = groupInfo.GroupFaceUrl; //新群组图标, 为空，则表示没有变化
      var newName = groupInfo.GroupName; //新群名称, 为空，则表示没有变化
      var newOwner = groupInfo.OwnerAccount; //新的群主id, 为空，则表示没有变化
      var newNotification = groupInfo.GroupNotification; //新的群公告, 为空，则表示没有变化
      var newIntroduction = groupInfo.GroupIntroduction; //新的群简介, 为空，则表示没有变化

      if (newName) {
        //更新群组列表的群名称
        //To do
        webim.Log.warn("群id=" + groupId + "的新名称为：" + newName);
      }
    }
  }
};
